<?php

require_once('dl_converter_functions.php');


//----------------------------
// SCRIPT
//----------------------------

// $dataFile = "DIR/data/20100610.txt";
// convertData2CO2($dataFile );
// $files = array($dataFile);
// generateCO2File("sensorId", time(), $files );


// $ids=getSensorIds();
// $sensorId = $ids[0];
// 
// echo $sensorId . "\n";
// $ts = time();
// //echo date(DATE_RFC822, $ts) . "\n";
// 
// //$ts = mktime($hour,$minute,$second,$month,$day,$year);
// $ts = mktime(13,58,59,2,22,2010);
// echo date(DATE_RFC822, $ts) . "\n";
// 
// 
// $time =  getNextDay($ts);
// echo date(DATE_RFC822, $time) . "\n";
// $time =  getLastDayOfTheMonth($time);
// echo date(DATE_RFC822, $time) . "\n";
// 
// 
// $files = getDataFiles($sensorId, $ts, $ts);
// echo $files[0] . "\n";
// 
// $t1=time() - 30*24*3600;
// $t2=getLastDayOfTheMonth( time()) ; 
// 
// $files = _getFilesBetweenDates('data',$t1,$t2 );
// print_r ($files);
// 
// $values = array( 2,3,4,5,6,7,3,4,2,6);
// $co2 = calculateCO2Value($values);
// $text = generateCO2Line($sensorId, $ts, $co2);
// echo $text; 
// 
// generateCO2Files($sensorId, $ts, $ts, 1);

//----------------------------
// MAIN FUNCTIONS
//----------------------------
// function getSensorIds(){
//   // returns a list with the sensor identifiers
//   $ids = array("SEN001");
//   return $ids;
// }

function generateCO2Files($sensorId, $startDay, $endDay, $clean){
  // (re-)generates the CO2 files 
  // within the specified period [start, end]
  global $DATA_DIR, $CO2_DIR;
  // cleanup, remove existing files
  if ($clean) {
    debugMessage("generateCO2Files:cleaning previous ...\n");
    $files = getCO2Files($sensorId, $startDay, $endDay);
//print_r($files);
    foreach ( $files as $file) {
      $source = $file;
      $target =  $CO2_DIR . "/_processed/" . basename($source);
      move_processed($source, $target);
      debugMessage("generateCO2Files:removed " . $source);
    }
  }
  // process files in month periods
  $startMonth = $startDay;
  do {
    $lastDay =  getLastDayOfTheMonth($startMonth);
    $files = getDataFiles($sensorId, $startMonth, $lastDay);
//echo "$startMonth ". date(DATE_RFC822, $startMonth) ."\n";
//echo "$lastDay ". date(DATE_RFC822, $lastDay) ."\n";
//print_r($files);    
    generateCO2File($sensorId, $startMonth, $files );
    //move processed files
    foreach ( $files as $file) {
      $source = $file;
      $target =  $DATA_DIR . "/_processed/" . basename($source);
      move_processed($source, $target);
      debugMessage("generateCO2Files:removed " . $source);
    }
    $startMonth = getNextDay($lastDay);
  } while ($lastDay < $endDay);
  
}

//----------------------------
// CO2 DATA PROCESSING FUNCTIONS
//----------------------------
function generateCO2File($sensorId, $startDay, $files){
  global $DATA_DIR, $CO2_DIR;
  $co2FileName = date('Ym', $startDay) .  "." . $sensorId ;
  $co2Path = $CO2_DIR . "/" . $co2FileName . ".txt";
  if (sizeof($files)<1) return;
  
  $file = fopen($co2Path,"w");
//echo '--------------' . $co2FileName . "\n";
  foreach ( $files as $filename) {
    debugMessage("generateCO2File:" . $filename); 
    // write
    $co2data = convertData2CO2($filename);
    foreach ( $co2data as $value ) {
      $line = generateCO2Line($sensorId, $value[0], $value[1]);
//echo $line;
      fwrite($file, $line);
    }
  }
  fclose($file);
//echo '--------------' . "\n";
}

function generateCO2Line($sensorId, $time, $co2){
  // generates 
  // SENS001.yyyymmddHHMMSS.co2
  $line = $sensorId. "," . date('Y,m,d,H,i',$time). "," . intval($co2) ."\n"; 
  return $line;
}

function calculateCO2Value($data){
  // algorithm that obtains a unique value of the period sampled data
  global $PPM_PER_VOLT;
  
  //basic mean value
  $co2 = 0;
  foreach ($data as $value){
    $co2=$co2+$value;
  }
  $co2 = $co2/ count($data);
  $co2 = intval($PPM_PER_VOLT * $co2);
  return $co2;
}

function convertData2CO2($dataFile){
  $index = 0;
  $counter =0;
  $buffer[0] = 0;
  $startTime = 0;

  $file = new SplFileObject($dataFile);
  foreach ($file as $k => $line) {
    $lineNumber = $file->key() + 1;
    $line =$file->current();
    if ($lineNumber >3) { // avoid headers
//      if ($lineNumber >50) break;
      $ts = get_timestamp($line);
      if ($startTime == 0) $startTime = $ts; 
      $voltage = getVoltage($line);
//echo $lineNumber . ': ' . $line . ":" . date(DATE_RFC822, $ts) . " voltage:" . $voltage . "\n";
      $buffer[$counter] = $voltage;
      $counter++;
//echo "seconds= $ts-$startTime\n";      
      if ($ts-$startTime > 60*10 ) {
//echo $lineNumber . ': ' . $line . ":" . $counter ."\n";
//print_r($buffer);
        // calculate mean value
        $co2 = calculateCO2Value($buffer);
//echo $co2 . "\n";
        $co2data[$index] = array($ts, $co2);
        $index++;
        //reset counters
        $counter =0;
        $buffer [0] = 0;
        $startTime = $ts;
      }
    }
  }
  return $co2data;
} 

//----------------------------
// AUXILIAR FUNCTIONS
//----------------------------

function getDataFiles($sensorId, $startDay, $endDay){
  // returns an data ordered list of existing data files 
  // within the specified period [start, end]
  global $DATA_DIR, $CO2_DIR;
  //$ids = array( $sensorId . "/20100701.txt", $sensorId . "/20100702.txt");
  $ids =  _getFilesBetweenDates($DATA_DIR, $startDay, $endDay);
  return $ids;
}  

function getCO2Files($sensorId, $startDay, $endDay){
  // returns an data ordered list of existing data files 
  // within the specified period [start, end]
  //$ids = array( $sensorId . "/201007.txt", $sensorId . "/201006.txt");
  global $DATA_DIR, $CO2_DIR;
  $ids =  _getFilesBetweenDates($CO2_DIR, $startDay, $endDay);
  return $ids;
}

function _getFilesBetweenDates($directory, $startDay, $endDay){
    $files = scandir($directory);
    $filenames = array();
    $index = 0;
//print_r($files);
//echo date(DATE_RFC822, $startDay) . "\n";
//echo date(DATE_RFC822, $endDay) . "\n";
    foreach ( $files as $file) {
      $time =  _getFilenameDate($file);
//echo date(DATE_RFC822, $time) . "\n";

//echo $startDay . "\n" . $time . "\n" . $endDay  ."----\n"; 
      if ( ($startDay <= $time) and ($time <= $endDay) ) {
        $filenames[$index] = $directory . "/" . $file;
        $index++;
      }
    }
    return $filenames;
}
function _getFilenameDate($filename){
  // yyyymm. or yyyymmdd.
  $year = substr($filename, 0,4);
  $month = substr($filename, 4,2);
  $day = substr($filename, 6,2);
  $token = substr($filename, 6,1);
  //echo $year . "_" .$month . "_" . $day . "\n";  
  $year = intval($year);
  $month = intval($month);
  $day = intval($day);
  if ($day == 0) $day = 11;
  //echo $year . "_" .$month . "_" . $day . "\n";
  $time = mktime(1,1,1,$month,$day,$year);
  return $time;
}

function debugMessage($message){
  echo $message."\n";
}

function getNextDay($time){
  $year = intval(date('Y', $time)); 
  $month = intval(date('m', $time));
  $day  = intval(date('d', $time));
  $ts = mktime(0,0,0,$month,$day,$year);
  $seconds_per_day = 24*3600;
  $ts = $ts + $seconds_per_day; 
  return $ts;
}
function getLastDayOfTheMonth($time){
  $seconds_per_day = 24*3600;
  $year = intval(date('Y', $time)); 
  $month = intval(date('m', $time))+1;
  if ($month>12){
    $month = 1;
    $year = $year+1;
  } 
  $day = 1; $hour = 23; $minute =  59; $second = 59;
  // 1st day of the next month 23:59:59 
  $ts = mktime($hour,$minute,$second,$month,$day,$year);
  // the previous day
  $ts = $ts - $seconds_per_day; 
  return $ts;
}

?>